package com.example.property.viewmodel

import androidx.lifecycle.viewModelScope
import com.example.common.vm.BaseViewModel
import com.example.property.intent.CarApplyViewIntent
import com.example.property.model.CarApplyRepository
import com.example.property.uistate.CarApplyUiState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject


/***/
@HiltViewModel
class CarApplyViewModel @Inject constructor(private val repository: CarApplyRepository) :BaseViewModel<CarApplyViewIntent>() {

    private val _uiState = MutableStateFlow<CarApplyUiState>(CarApplyUiState.NullState)
    val uiState :StateFlow<CarApplyUiState> =_uiState.asStateFlow()

    override fun dispatchIntent(intent: CarApplyViewIntent) {
        when(intent){
            is CarApplyViewIntent.LoadCarApplyList->loadCarApplyList()
        }
    }

    private fun loadCarApplyList() {
        viewModelScope.launch (Dispatchers.IO){
            try {
                var result =repository.getCarApplyList()
                if (result.statuesCode=="200"){
                    _uiState.value=CarApplyUiState.LoadCarApplySuccess(result.getValues())
                }else{
                    _uiState.value=CarApplyUiState.LoadCarApplyFail(result.msg?:"接口加载失败: ")
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }finally {
                cancel()
            }
        }
    }
}